package com.sunlands.zlcx.usercenter.controller;

import com.sunlands.zlcx.usercenter.common.annotation.AuthSig;
import com.sunlands.zlcx.usercenter.common.annotation.AutoLog;
import com.sunlands.zlcx.usercenter.common.cache.RedisDistributedLockImpl;
import com.sunlands.zlcx.usercenter.constant.YN;
import com.sunlands.zlcx.usercenter.domain.ParentTargetDO;
import com.sunlands.zlcx.usercenter.domain.TargetDO;
import com.sunlands.zlcx.usercenter.exception.CheckRunException;
import com.sunlands.zlcx.usercenter.exception.GlobalExceptionHandler;
import com.sunlands.zlcx.usercenter.exception.PlatformException;
import com.sunlands.zlcx.usercenter.service.TargetServiceImpl;
import com.sunlands.zlcx.usercenter.service.UsersServiceImpl;
import com.sunlands.zlcx.usercenter.util.AsyncTaskManager;
import com.sunlands.zlcx.usercenter.vo.*;
import com.sunlands.zlcx.usercenter.vo.response.BusinessResult;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
import static com.sunlands.zlcx.usercenter.common.annotation.AutoLog.Level.DEBUG;
import static com.sunlands.zlcx.usercenter.vo.CommonResultMessage.PARAMS_NOT_INVALIDE;
import static com.sunlands.zlcx.usercenter.vo.CommonResultMessage.UNKOWN_ERROR;

/**
 * @author 郜炎峰
 * description: 学习目标
 */
@SuppressWarnings("unused")
@Api(tags = "3、目标信息", position = 3)
@ApiResponses(value = {@ApiResponse(code = 400, response = GlobalExceptionHandler.class, message = "数据校验失败"), @ApiResponse(code = 500, response = GlobalExceptionHandler.class, message = "内部错误")})
@Slf4j
@RestController
@RequestMapping("/target")
public class TargetController extends BaseController implements AuthSupport {

    @AutoLog(logLevel = DEBUG)
    @ApiOperation(value = "目标列表", notes = "目标列表", response = ParentTargetVO.class)
    @GetMapping("/exam/list")
    @AuthSig
    public BusinessResult targetList(@ApiParam(required = true, value = "目标类型, 0:考试，1:其它") @RequestParam Integer targetType) {
        try {
            if (null == targetType || null == ParentTargetDO.TargetEnums.create(targetType)) {
                return BusinessResult.createInstance(PARAMS_NOT_INVALIDE);
            }
            List<ParentTargetVO> parentTargetVOList = targetService.examList(targetType);
            return BusinessResult.createSuccessInstance(parentTargetVOList);
        } catch (PlatformException ex) {
            log.error("", ex);
            return BusinessResult.createInstance(UNKOWN_ERROR.code, ex.getMessage(), ex.getMessage());
        } catch (Exception ex) {
            log.error("", ex);
            return BusinessResult.createInstance(UNKOWN_ERROR, "未知异常");
        }
    }

    @AutoLog
    @ApiOperation(value = "新增目标", notes = "新增目标")
    @PostMapping("/edit/target")
    @AuthSig
    public BusinessResult addTarget(@ApiParam(required = true, value = "目标VO") @RequestBody TargetVO targetVO) {
        String checkAddTarget = checkAddTarget(targetVO);
        if (null != checkAddTarget) {
            return BusinessResult.createInstance(PARAMS_NOT_INVALIDE, checkAddTarget);
        }
        TargetDO targetDO = targetService.addTarget(targetVO);
        return BusinessResult.createSuccessInstance(targetDO);
    }

    @AutoLog
    @ApiOperation(value = "新增父目标", notes = "新增父目标")
    @PostMapping("/edit/parent/target")
    @AuthSig
    public BusinessResult addParentTarget(@ApiParam(required = true, value = "父目标VO") @RequestBody ParentTargetVO parentTargetVO) {

        String checkAddTarget = checkAddParentTarget(parentTargetVO);
        if (null != checkAddTarget) {
            return BusinessResult.createInstance(PARAMS_NOT_INVALIDE, checkAddTarget);
        }
        targetService.addParentTarget(parentTargetVO);
        return BusinessResult.createSuccessInstance(null);

    }

    @AutoLog
    @ApiOperation(value = "新增用户目标", notes = "新增用户学习目标")
    @PostMapping("/user/add/target")
    @AuthSig
    public BusinessResult addUserTarget(@ApiParam(required = true, value = "用户目标VO") @RequestBody UsersTargetRelationVO usersTargetRelationVO) {
        try {
            String checkAddTarget = checkUserAddTarget(usersTargetRelationVO);
            if (null != checkAddTarget) {
                return BusinessResult.createInstance(PARAMS_NOT_INVALIDE, checkAddTarget);
            }
            redisDistributedLock.openUserLock(usersTargetRelationVO.getUserId());
            targetService.addUserTarget(usersTargetRelationVO);
            return BusinessResult.createSuccessInstance(null);
        } catch (PlatformException ex) {
            log.error("", ex);
            return BusinessResult.createInstance(UNKOWN_ERROR.code, ex.getMessage(), ex.getMessage());
        } catch (Exception ex) {
            log.error("", ex);
            return BusinessResult.createInstance(UNKOWN_ERROR, "未知异常");
        } finally {
            redisDistributedLock.releaseUserLock(usersTargetRelationVO.getUserId());
        }
    }

    @AutoLog
    @ApiOperation(value = "存档用户目标", notes = "存档学习目标")
    @PostMapping("/user/over/target")
    @PreAuthorize("isAuthenticated()")
    @AuthSig
    public BusinessResult overTarget(@ApiParam(required = true, value = "用户目标VO") @RequestBody UsersTargetRelationVO usersTargetRelationVO) {
        try {

            String checkAddTarget = checkUserEditTarget(usersTargetRelationVO);
            if (null != checkAddTarget) {
                return BusinessResult.createInstance(PARAMS_NOT_INVALIDE, checkAddTarget);
            }
            targetService.overUserTarget(usersTargetRelationVO, false);
            return BusinessResult.createSuccessInstance(null);

        } catch (PlatformException ex) {
            log.error("", ex);
            return BusinessResult.createInstance(UNKOWN_ERROR, "平台运行异常，请联系管理员");
        } catch (Exception ex) {
            log.error("", ex);
            return BusinessResult.createInstance(UNKOWN_ERROR, "未知异常");
        }
    }

    @AutoLog
    @ApiOperation(value = "删除用户目标", notes = "删除学习目标")
    @PostMapping("/user/delete/target")
    @PreAuthorize("isAuthenticated()")
    public BusinessResult deleteTarget(@ApiParam(required = true, value = "用户目标VO") @RequestBody UsersTargetRelationVO usersTargetRelationVO) throws ExecutionException {
        String checkAddTarget = checkUserEditTarget(usersTargetRelationVO);
        if (null != checkAddTarget) {
            return BusinessResult.createInstance(PARAMS_NOT_INVALIDE, checkAddTarget);
        }
        targetService.overUserTarget(usersTargetRelationVO, true);
        return BusinessResult.createSuccessInstance(null);
    }

    @AutoLog
    @ApiOperation(value = "获取用户目标", notes = "获取用户目标", response = UsersTargetRelationVO.class)
    @GetMapping("/get/user/target/{userId}")
    @PreAuthorize("isAuthenticated()")
    @AuthSig
    public BusinessResult getUserTarget(@ApiParam(required = true, value = "用户id") @PathVariable Long userId) {
//            userId = currentUserId();
        if (null == userId) {
            return BusinessResult.createInstance(CommonResultMessage.INVALID_USER);
        }
        if (null == usersService.find(userId)) {
            throw new CheckRunException("用户不存在");
        }
        UsersTargetRelationVO usersTargetRelationVO = targetService.getUserTarget(userId);
        return BusinessResult.createSuccessInstance(usersTargetRelationVO);

    }


    private String checkUserAddTarget(UsersTargetRelationVO usersTargetRelationVO) {
        if (null == usersTargetRelationVO) {
            return "用户目标VO不能为空";
//        }else if (null == usersTargetRelationVO.getTargetId()) {
//            return "目标id不能为空";
        } else if (null == usersTargetRelationVO.getUserId()) {
            return "用户id不能为空";
        } else if (null == usersService.find(usersTargetRelationVO.getUserId())) {
            return "用户不存在" + usersTargetRelationVO.getUserId();
        }
        return null;
    }

    private String checkUserEditTarget(UsersTargetRelationVO usersTargetRelationVO) {
        if (null == usersTargetRelationVO) {
            return "用户目标VO不能为空";
        }
        return null;
    }

    private String checkAddTarget(TargetVO targetVO) {
        if (null == targetVO) {
            return "目标VO不能为空";
        } else if (null == targetVO.getTargetName()) {
            return "目标名称不能为空";
        } else if (null != targetVO.getStatus() && null == YN.create(targetVO.getStatus())) {
            return "状态值错误";
        } else if (null == targetVO.getParentId()) {
            return "父目标id不能为空";
        } else if (null != targetVO.getId() && null == targetVO.getOrders()) {
            return "目标排序错误";
        }
        return null;
    }

    private String checkAddParentTarget(ParentTargetVO parentTargetVO) {
        if (null == parentTargetVO) {
            return "父目标VO不能为空";
        } else if (null == parentTargetVO.getTargetName()) {
            return "父目标名称不能为空";
        } else if (null != parentTargetVO.getStatus() && null == YN.create(parentTargetVO.getStatus())) {
            return "状态值错误";
        } else if (null != parentTargetVO.getId() && null == parentTargetVO.getOrders()) {
            return "父目标排序错误";
        }
        return null;
    }

    private final TargetServiceImpl targetService;
    private final UsersServiceImpl usersService;
    private final AsyncTaskManager asyncTaskManager;
    @Autowired
    private RedisDistributedLockImpl redisDistributedLock;

    public TargetController(TargetServiceImpl targetService, UsersServiceImpl usersService, AsyncTaskManager asyncTaskManager) {
        this.targetService = targetService;
        this.usersService = usersService;
        this.asyncTaskManager = asyncTaskManager;
    }

}
